package LeetCode;

/**
 * @Author: Dijah
 * @Date: 2023/1/12 16:23
 * @Desc: 二叉树展开为链表
 */
public class code114_flatten {

    public static class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
    }

    public static void flatten(TreeNode root){
        if(root == null){
            return;
        }
        //把左右子树拉平
        flatten(root.left);
        flatten(root.right);
        //后续遍历位置，将树拉成一条链表
        TreeNode left = root.left;
        TreeNode right = root.right;

        //将左子树作为右子树
        root.left = null;
        root.right = left;

        //将以前的右子树对接到，上一步的将左子树作为右子树的右子树上
        TreeNode p = root;
        while(p.right != null){
            p = p.right;
        }
        p.right = right;
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        node1.left = node2;
        node1.right = node5;
        node2.left = node3;
        node2.right = node4;
        node5.right = node6;
        flatten(node1);
    }
}
